var createError = require('http-errors');
var express = require('express');
const session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs = require('ejs');
var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');
var adConfigRouter = require('./routes/adconfig');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.engine('.html',ejs.__express);
// app.engine('html', ejs.renderFile);
// app.set('view engine', "html");

app.engine('.ejs',ejs.__express);
app.set('view engine','ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

var mongoose = require('mongoose');     
      
//mongoose.connect('mongodb://adpush_server_account:adpush20200909sc@localhost:27017/AdPushDB')
mongoose.connect('mongodb://localhost:27017/AdPushDB?poolSize=40')
var db = mongoose.connection;
// 连接成功
db.on('open', function(){
    console.log('MongoDB Connection Successed');
});
// 连接失败
db.on('error', function(){
    console.log('MongoDB Connection Error');
});

//session配置要放在获取路由前面
app.use(session({
  name:"teapp",
  secret : 'secret_123456', // 对session id 相关的cookie 进行签名
  resave : false,
  saveUninitialized: true, // 是否保存未初始化的会话
  cookie : {
    maxAge : 1000 * 60 * 60 * 24, // 设置 session 的有效时间，单位毫秒
  },
}));

//public文件夹是网站的静态资源公共访问目录，比如可以访问http://localhost:3000/images/kiss.png
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/admin', adminRouter);
app.use('/adconfig', adConfigRouter);




// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;
